'''
表操作及插入数据
Created on 2017年3月16日

@author: mark
'''
import pymysql
from pymysql.err import MySQLError

'''
获取数据库连接
'''
def getConn():
    hostAddr = 'localhost'  # 主机地址
    userName = 'root'  # 用户名
    password = ''  # 密码
    databseName = 'test'  # 数据库名
    db = pymysql.connect(hostAddr, userName, password, databseName)
    return db

#创建表
def createTable(db):
    try:
        with db.cursor() as cursor:
            sql = "CREATE TABLE `test` (\
            `id` int(11) NOT NULL,\
            `descript` varchar(255) DEFAULT NULL,\
            PRIMARY KEY (`id`))"
            cursor.execute(sql)
    except Exception:
            db.rollback()
            print("执行出错")
            
def save(db):
    try:
        with db.cursor() as cursor:
            sql = "insert into test values(123,'this is test')"
            cursor.execute(sql)
            db.commit()
            return True
    except MySQLError:  
        db.rollback()
        print("执行出错，回滚")  
        return False
        
#测试    
db = getConn()
# createTable(db)
print(save(db))